var base64 = require('../../we7/resource/js/base64.js');
import GoEasy from './goeasy/goeasy-1.0.6';
var app = getApp();
Page({
    data:{
        inited : false,
        sharedata : {},
		siteroot : app.siteInfo.siteroot.replace('app/index.php', ''),uniacid: app.siteInfo.uniacid,
        datalist : [],
        liveCurrent : 0,
        addIndex : 1,
        isshowGoods : true,
        isshowbot : true,
        orientation : 'vertical',
        playurl : '',
        page : {
            isend : false,
            doing : false,
            doo : 'live',
            pdata : {
                op : 'list',
                page : 1,
                otype : 0,
                vtype : 1,
                num : 20,
                id : 0,
                from : 'live',
            },
            waitf : 0,
            nodataf : 0,
        },
        info : {},
        goods : {},
        loading : true,
        showAnim : false,
        gift : false,
        isshowgift : false,
        giftActive : -1,
        userinfo : {},
        nowNum : 1,
        socketNum : [ {
                num: 1314,
                name: "一生一世"
            }, {
                num: 520,
                name: "我爱你"
            }, {
                num: 188,
                name: "要发发"
            }, {
                num: 66,
                name: "666"
            }, {
                num: 10,
                name: "十全十美"
            }, {
                num: 1,
                name: "一心一意"
        }],
        nowNumShop : false,
        socketGiftData : [],
        animation5 : false,
        actgoods : {},
        chouinfo : {},
        isinit : false,
        iconPlayShow :false,
        VideoContext : null,
        numtimer : null,
        liver : null,
        showlive : true,
        playercode : 0,
    },
    onShow(){
        if(this.data.inited){
            var self = this;
            var postdata = {
                op:'getuserinfo',
            }
            app.com.http('live','POST',postdata,0,false,'','',function(res){
                if (!res.data.errno && res.data) {
                    self.setData({
                        userinfo : res.data.data.userinfo
                    })
                }
            });
        }
    },
    onLoad:function(options){
        var self = this;
        if( options.scene ){
            var list = options.scene.split('_');
            options.id = list[0] ? list[0] : 0;
            options.zfid = list[1] ? list[1] : 0;
        }
        var id = options.id ? options.id : '';
        var zfid = options.zfid ? options.zfid : '';

        app.com.getLocation(self,function(loc){
            self.setData({
                'page.pdata.lat' : loc.latitude,
                'page.pdata.lng' : loc.longitude,
                'page.pdata.id' : id,
                'page.pdata.zfid' : zfid,
            });
            app.com.auth(function(user){
                app.com.getPage(self,self.data.page,20,function(res){
                    var data = res.data.data;
                    self.setData({
                       datalist : data.list,
                       info : data.info,
                       params : data.params,
                       goods : data.goods,
                       userinfo : data.userinfo,
                       actgoods : data.actgoods ? data.actgoods : {},
                       chouinfo : data.chouinfo ? data.chouinfo : {},
                       sharedata : data.sharedata,
                       'page.pdata.id' : 0,
                       inited : true,
                    },function(){
                        self.initGo('live'+self.data.info.code);
                        if( data.joinmess ){
                            app.com.sendGo(data.joinmess.mess,data.joinmess.channel);
                        }
                        self.getNumber();
                    });
                },false,function(res){
                    app.com.alert(res.data.message,function(){
                        app.com.backPage(zfid);
                    });
                });
            });
        });
    },
    onUnload(){
        if(app.globalData.goEasy){
            app.globalData.goEasy.disconnect();
            app.globalData.goEasy = false;
        }
    },
    onShareAppMessage : function(){
        var self = this;
        return {
            title: self.data.sharedata.title,
            path: self.data.sharedata.path,
            imageUrl : self.data.sharedata.img,
            complete : function(e){
                app.com.alert('1');
            }
        }
    },
    onPlayEvent: function(e) {
        var self = this;

        switch (console.log("======>"+e.detail.code), e.detail.code) {
          case 2004:
            if(this.data.isinit){
                this.setData({
                    showloading : false,
                })
            }
            console.log('code2004')
            this.setData({
                showAnim : true,
                isinit : true,
            })
            this.playstart();
            setTimeout(function() {
                self.setData({
                    showAnim : false,
                    loading : false,
                })
            }, 600);
            
            break;
          case 2007:

            if(this.data.isinit){
                this.setData({
                    showloading : true,
                })
            }else{
                this.setData({
                    loading : true,
                })
            }
            break;
          case 2105:
            break;
          case -2301:
            wx.showToast({
                title: "网络不稳定，请上下滑动重新刷新直播间",
                icon: "none"
            });
        }
    },
    changeSwiper(e){
        var self = this;
        self.setData({
            addIndex : 1,
            loading : true,
            liveCurrent : e.detail.current,
            isShowPlayBtn : false,
            isShowPosterBar : false,
            showloading : false,
            isinit : false,
            iconPlayShow : false,
        })
        var postdata = {
            op:'getlive',
            liveid : this.data.datalist[this.data.liveCurrent].id
        }
        /*if(this.data.liver){
            this.data.liver.stop();
        }*/

        self.selectComponent('#chatbar').clear();
        app.com.http('live','POST',postdata,0,false,'','',function(res){
            if (!res.data.errno && res.data) {

                var oldcode = self.data.info.code;
                self.setData({
                    info : res.data.data.info,
                    sharedata : res.data.data.sharedata,
                    goods : res.data.data.goods ? res.data.data.goods : [],
                    actgoods : res.data.data.actgoods ? res.data.data.actgoods : {},
                    chouinfo : res.data.data.chouinfo ? res.data.data.chouinfo : {},
                },function(){
                    self.initGo('live'+self.data.info.code,'live'+oldcode);
                    if( res.data.data.joinmess ){
                        app.com.sendGo(res.data.data.joinmess.mess,res.data.data.joinmess.channel);
                    }
                });
            }
        });
    },
    getNumber(){
        var self = this;
        clearInterval(self.data.numtimer);
        self.data.numtimer = setInterval(function(){
            var postdata = {
                op:'getnumber',
                id:self.data.info.id
            }
            app.com.http('live','POST',postdata,0,false,'','',function(res){
                if (!res.data.errno && res.data) {
                    self.setData({
                        'info.zan' : res.data.data.zan,
                        'info.renqi' : res.data.data.renqi,
                        'info.totalrq' : res.data.data.totalrq,
                    })
                }
            })
        },10000)
    },
    bindnetstatus(e){
        console.log(e)
    },
    onOrientationClick() {
        this.setData({
            orientation : this.orientation = "horizontal" ? 'vertical' : 'horizontal'
        })
    },
    showbag(e){
        this.setData({
            isshowGoods : e.detail == 1 ? false : true,
        })
    },
    showbotbar(e){
        this.setData({
            isshowbot :  e.detail == 1 ? false : true,
        })
    },
    showbagfn(e){
        this.selectComponent('#goodsmask').onClose();
    },
    pauseVideo(){
        if(this.data.info.isback == 1 && this.data.info.playstatus == 7){
            console.log('1')
            //video.pause()
            this.setData({
                iconPlayShow : !this.data.iconPlayShow,
            })
        }
    },
    playvideo(){
        if( this.data.VideoContext ){
            var video = this.data.VideoContext;
        }else{
            var video = this.data.VideoContext = wx.createVideoContext('vinfo'+this.data.liveCurrent);
        }
        video.play()
        this.setData({
            iconPlayShow : false,
        })
    },
    shareit(){
        this.selectComponent('#poster').onClose();
    },
    initGo(channel,oldchannel){
        var self = this;
        if(!app.globalData.goEasy){
            app.globalData.goEasy = new GoEasy({
                host: self.data.params ? self.data.params.gosite : '', 
                appkey: self.data.params ? base64.base64_decode(self.data.params.gokey) : '',
                userId : self.data.params.uid,
                onConnected: function() {
                    console.log('go连接成功！')
                },
                onDisconnected: function() {
                    console.log('go连接断开！')
                },
                onConnectFailed: function(error) {
                    console.log('go连接失败或错误！',error)
                }
            });
        }
        if(oldchannel){
            app.globalData.goEasy.unsubscribe({
                channel : oldchannel
            });
            //console.log(oldchannel)
        }
        app.globalData.goEasy.subscribe({
            channel: channel,
            onMessage: function (message) {
                self.setMessage(message.content);
            }
        });
    },
    setMessage(mess){
        var self = this;
        var content = JSON.parse(mess);
        // 消息
        if(content.mtype == 'mess'){
            self.selectComponent('#chatbar').addMessage(content);
        }
        if(content.type == 'zan'){
            self.selectComponent('#bottombar').addzan();
        }else if(content.type == 'close'){
            this.setData({
                'info.playstatus' : 8,
            })
        }else if(content.type == 'open'){
            
            console.log('open');
            self.setData({
                showlive : false,
            })
            setTimeout(function(){
                self.setData({
                    showlive : true,
                })
            },50)

        }else if(content.type == 'gift'){          
            self.onSendGift(content);

        }else if(content.type == 'downgoods'){  
            self.setData({
                actgoods : false,
            })

        }else if(content.type == 'pubchou'){
            self.selectComponent('#chou').upprize();
        }else if(content.type == 'openchou'){
            self.selectComponent('#chou').upprize();

        }else if(content.type == 'pushgoods'){          
            
            for (var i = 0; i < self.data.goods.length; i++) {
                if(self.data.goods[i].id*1 == content.gid*1){
                    self.setData({
                        actgoods : self.data.goods[i]
                    })
                }
            }

        }else if(content.type == 'hidegoods' || content.type == 'showgoods' || content.type == 'delgoods'){

            for (var i = 0; i < this.data.goods.length; i++) {
                
                if(this.data.goods[i].id*1 == content.gid*1){
                    if(content.type == 'hidegoods'){
                        this.setData({
                            ['goods['+i+'].ishideitem'] : 1
                        })
                    }else if(content.type == 'showgoods'){
                        this.setData({
                            ['goods['+i+'].ishideitem'] : 0
                        })
                    }else if(content.type == 'delgoods'){
                        this.data.goods.splice(i,1);
                        this.setData({
                            goods : this.data.goods
                        })
                    }
                }
            }
        }
    },
    showBubble(){
        this.selectComponent("#bubble").showBubble();
    },
    showgift(){
        var self = this;
        if(self.data.ising) return false;
        self.data.ising = true;

        if(!self.data.gift){
            var postdata = {
                op : 'getgift',
                liveid :  self.data.info.id,
            };
            app.com.http('live','POST',postdata,0,true,'','',function(res){
                if ( !res.data.errno && res.data.errno !== undefined ) {
                    self.setData({
                        gift : res.data.data.gift,
                        isshowgift : true,
                    })
                }else{
                    app.com.toast(res.data.message);
                }
                self.data.ising = false;
            }); 
        }else{
            self.setData({
                isshowgift : true,
            })
            self.data.ising = false;
        }
    },
    onClosegift(){
        this.setData({
            isshowgift : !this.data.isshowgift
        })
    },
    onselectGift(e){
        var i = e.currentTarget.dataset.i;
        this.setData({
            giftActive : i,
        })
    },
    nowNumShopNum(){
        this.setData({
            nowNumShop : !this.data.nowNumShop,
        })
    },
    onNumClick(){

    },
    onNowNumShop(e){
        this.setData({
            nowNum : e.currentTarget.dataset.num,
            nowNumShop : false,
        })
    },
    onNowSendGift(){
        var self = this;
        if(this.data.giftActive < 0){
            app.com.toast('还没选择礼物');
            return false;
        }
        var postdata = {
            op : 'sendgift',
            liveid :  self.data.info.id,
            giftid : self.data.gift[self.data.giftActive].id,
            num : self.data.nowNum,
        };
        if(self.data.ising) return false;
        self.data.ising = true;

        app.com.http('live','POST',postdata,0,true,'','',function(res){
            if ( !res.data.errno && res.data.errno !== undefined ) {
                //self.onSendGift({id:1,num:10});
                self.setData({
                    'userinfo.umoney' : res.data.data.lastmoney,
                })
                if( res.data.data.mess ){
                    
                    if(res.data.data.istoall == 0){
                        var mess = JSON.parse(res.data.data.mess);
                        self.onSendGift(mess);
                        app.com.sendGo(res.data.data.mess,res.data.data.channel,1);
                    }else{
                        app.com.sendGo(res.data.data.mess,res.data.data.channel);
                    }
                }
            }else{
                app.com.toast(res.data.message);
            }
            self.data.ising = false;
        }); 
    },
    onSendGift: function(t) {
        var self = this;
        var e = this.data.socketGiftData;
        for (var i = 0; i < e.length; i++) e[i].id == t.id && (t.num = parseInt(t.num) + parseInt(e[i].num), 
        e.splice(i, 1));
        e.push(t), 2 < e.length && (e = e.slice(1));

        this.setData({
            isshowanim : true,
        },function(){
            var n = wx.createAnimation({
                duration: 500,
                timingFunction: "ease"
            });
            n.translateX(0).step();
            this.setData({
                animation5: n.export(),
                socketGiftData: e
            });
            this.data.tiemOuter && clearTimeout(this.data.tiemOuter);
            this.data.tiemOuter = setTimeout(function() {
                self.onHideGift()
                self.setData({
                    socketGiftData: []
                });
            },3000);
        })
    },
    onHideGift: function() {
        var t = wx.createAnimation({
            duration: 500,
            timingFunction: "ease"
        });
        t.translateX("-100%").step();
        this.setData({
            animation5: t.export(),
            isshowanim : false,
        });
    },
    playstart(){
        var self = this;
        self.setData({
            'info.playstatus' : 10,
            ['datalist['+self.data.liveCurrent+'].playstatus'] : 10,
        })

    },
    navigateto : function( e ){
        app.com.navigateto( e );
    },
    binddy(e){
        var self = this;
        var type = e.detail.type;
        self.setData({
            ['info.'+type] : e.detail.value,
        })
    }
})